<template>
  <div class="gdinfo">
    <img :src="gdinfo.coverImgUrl" alt="">
    <div class="info">
      <b>{{ gdinfo.name }}</b>
      <el-text line-clamp="2">
        {{ gdinfo.description }}
      </el-text>
      <div class="createuer">
        <el-avatar :src="gdinfo.avatarUrl" :size="25" />
        <span>{{ gdinfo.nickname }}</span><br />
        <span>标签： {{ gdinfo.tags }}</span>
        <span>{{ gdinfo.createTime }}创建</span>
      </div>
      <div class="playbtns">
        <el-button type="success"  v-if="playStore.playListId===Number(playlistId) && playStore.isPlayed" @click="playAll">
          <el-icon>
            <i-bi-pause-circle />
          </el-icon>
          暂停播放
        </el-button>
        <el-button type="danger" v-else @click="playAll">
          <el-icon>
            <i-bi-caret-right-fill  />
          </el-icon>
          立即播放
        </el-button>
        <el-button>
          <el-icon>
            <i-bi-box2-heart />
          </el-icon>
          收藏
        </el-button>
        <el-button>
          <el-icon>
            <i-bi-cloud-download />
          </el-icon>
          下载
        </el-button>
        <el-button v-if="isself" @click="deletePlaylist">
          <el-icon>
            <i-bi-trash3 />
          </el-icon>
          删除
        </el-button>
      </div>
    </div>
  </div>
  <div class="mytab">
    <el-tabs v-model="activeTab" @tab-change="changeTab">
      <el-tab-pane label="歌曲" name="table">
        <SongTable :tableData="songs" :height="height" v-loading="loading" element-loading-background="transparent" />
      </el-tab-pane>
      <el-tab-pane label="评论" name="comments">
        <comment :comments="commons"/>
      </el-tab-pane>
      <el-tab-pane label="收藏者" name="collect">
        收藏者列表
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup lang="ts">
import { topRankList, deleteplaylist,playlistComment } from '@/assets/apis/http'
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter,onBeforeRouteUpdate } from 'vue-router'
import { Song, PlayListDetail,Common,CommonbBeReplied } from '@/assets/apis/MusicDataType'
import util from '@/tools/util'
import { useUserStore } from '@/store/UserStore'
import { usePlayStore } from '@/store/PlayStore'
import emitter from '@/store/emitter'

// 获取路由参数
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const playStore = usePlayStore()
//歌单信息
const gdinfo = reactive<PlayListDetail>({
  id: 1,
  name: '我的最爱',
  coverImgUrl: 'https://example.com/cover.jpg',
  tags: ['流行', '摇滚'],
  description: '这是我最喜欢的播放列表',
  createTime: '2024-01-11',
  playCount: 1000,
  songCount: 10,
  nickname: '张三',
  avatarUrl: 'https://example.com/avatar.jpg',
  userId: 123,
  subscribedCount: 123
})
const safeHeight = 'calc(100vh - 340px)'
const height = ref(safeHeight)
const commonCount = ref(0)

//歌曲信息
const songs = reactive<Song[]>([])
const activeTab = ref<string>('table')
const playlistId = ref<string>('')
const loading = ref(false)
const commons = reactive<Common[]>([])
const isself = computed(() => {
  const userId = userStore.userInfo.userId
  const paramId = (Number)(gdinfo.userId + '')
  return paramId === userId
})

//删除歌单
async function deletePlaylist() {
  const res = await deleteplaylist({ id: gdinfo.id })
  console.log('删除歌单回调', res)
  router.go(-1)
}
async function changeTab(tab: string) {
  if (tab === "comments" && commons.length === 0) {
    getCommons()
  }
}
async function getCommons() {
  const res = await playlistComment({ id: playlistId.value, pageNum: 1 })
  commonCount.value = res.total
  let commonlist = res.comments.map(item => {
    let icon = ""
    if (item.user.vipRights && item.user.vipRights.associator) {
      icon = util.formatSongsPic(item.user.vipRights.associator.iconUrl);
    }
    let beReplied = <CommonbBeReplied[]>[]
    if (item.beReplied) {
      beReplied.push(...item.beReplied.map(item => {
        return {
          commentId: item.beRepliedCommentId,
          content: item.content,
          nickname: item.user.nickname,
          avatarUrl: util.formatSongsPic(item.user.avatarUrl, 50),
          userId: item.user.userId
        }
      }))
    }
    return {
      commentId: item.commentId,
      content: item.content,
      timeStr: item.timeStr,
      nickname: item.user.nickname,
      avatarUrl: util.formatSongsPic(item.user.avatarUrl, 50),
      vipRights: icon,
      userId: item.user.userId,
      vipType: item.user.vipType,
      userType: item.user.userType,
      likedCount: item.likedCount,
      beReplied: beReplied
    }
  })
  console.log('歌单评论列表', commonlist)
  commons.splice(0,commons.length,...commonlist)
}
function playAll() {
  if (playStore.playListId===Number(playlistId.value)) {
    emitter.emit('playAudioType', 'play')
  } else {
    playStore.playAll(songs)
    playStore.playListId = Number(playlistId.value)
  }
}

async function getGdInfo() {
  loading.value = true
  try {
    const res = await topRankList({ id: playlistId.value, s: 0 })

    let newgedan = {
      id: res.playlist.id,
      name: res.playlist.name,
      description: res.playlist.description,
      tags: res.playlist.tags.map(obj => obj).join('/'),
      coverImgUrl: util.formatSongsPic(res.playlist.coverImgUrl, 300),
      createTime: new Date(res.playlist.createTime).toLocaleString(),
      nickname: res.playlist.creator.nickname,       //创建人
      avatarUrl: util.formatSongsPic(res.playlist.creator.avatarUrl, 300),
      userId: res.playlist.creator.userId,           //创建人id
      playCount: res.playlist.playCount,             //播放数
      subscribedCount: res.playlist.subscribedCount, //收藏数
      songCount: res.playlist.tracks.length          //歌曲数
    }
    Object.assign(gdinfo, newgedan)

    const songsList = res.playlist.tracks
    //console.log("歌单歌曲信息",songsList)
    songs.splice(0, songs.length, ...songsList.map(songItem => {
      return {
        id: songItem.id,
        name: songItem.name,
        albumPic: util.formatSongsPic(songItem.al.picUrl, 300),
        album: songItem.al.name,
        singer: songItem.ar.map(({ name, id }) => ({ name, id })),
        alia: songItem.alia[0],
        duration: songItem.dt,
        fee: songItem.fee,
        publishTime: songItem.publishTime,
        mvId: songItem.mv,
        license: songItem.cp,
        url: 'https://music.163.com/song/media/outer/url?id=' + songItem.id + '.mp3'
      }
    }))
    console.log('处理后歌曲列表', songs)
  } catch (error) {
    console.error('获取歌单信息失败：', error)
  } finally {
    loading.value = false
  }
}

// 获取歌单信息的方法
const initGedanData = (id: string) => {
  console.log("歌单id：", id);
  if (id) {
    playlistId.value = id
    getGdInfo()
    getCommons()
  }
}

// 组件首次加载
onMounted(() => {
  const id = route.params.id as string
  initGedanData(id)
})

// 路由参数更新时（同一组件内切换不同歌单）
onBeforeRouteUpdate((to) => {
  const id = to.params.id as string
  initGedanData(id)
})
</script>
<style scoped lang="scss">
.gdinfo {
  margin-left: 30px;
  margin-right: 30px;
  display: flex;
  color: var(--el-text-color-primary);

  img {
    width: 180px;
    border-radius: 20px;
    margin-right: 20px;
  }

  .info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 180px;

    b {
      font-size: 20px;
    }

    .createuer {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-top: 7px;
    }

    .playbtns i {
      margin-right: 8px;
    }
  }
}

.mytab {
  margin: 10px 30px 0 30px;

  :deep(.el-tabs__item) {
    font-size: 18px;
  }
}
</style>
